package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.txg.module.home.entity.MarketCateResponse
import com.zhkj.txg.module.home.entity.TopDataResponse
import com.zhkj.txg.module.home.entity.TopProductResponse
import com.zhkj.txg.module.home.model.HomeManager

@Suppress("UNCHECKED_CAST")
class MarketViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager = HomeManager()
    val marketLiveData = MutableLiveData<HttpResponse<TopDataResponse>>()
    val marketCateLiveData = MutableLiveData<HttpResponse<MarketCateResponse>>()
    val marketProductLiveData = MutableLiveData<HttpResponse<TopProductResponse>>()

    private var page = 1
    private val numb = 20

    fun marketData(token: String) {
        val listener = object : ViewModelSubscribeListener<TopDataResponse>(marketLiveData) {
            override fun onSuccess(resp: TopDataResponse) {
                super.onSuccess(resp)
                page = 1
                marketProduct(token)
            }
        }
        val marketData = homeManager.marketData(token, listener)
        dispose.add(marketData)
    }

    fun marketProduct(token: String) {
        val listener =
            object : ViewModelSubscribeListener<TopProductResponse>(marketProductLiveData) {
                override fun onSuccess(resp: TopProductResponse) {
                    resp.hasMore = resp.data.size >= numb
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        val marketProduct = homeManager.marketProduct(token, page, numb, listener)
        dispose.add(marketProduct)
    }

    fun marketCate(token: String, catId: Int) {
        val listener = object : ViewModelSubscribeListener<MarketCateResponse>(marketCateLiveData) {
            override fun onSuccess(resp: MarketCateResponse) {
                resp.data?.let {
                    if (it.category.isNotEmpty()) it.category[0].selected = true
                }
                super.onSuccess(resp)
            }
        }
        val marketCate =
            homeManager.marketCate(token, catId, listener)
        dispose.add(marketCate)
    }

    fun secondCate(token: String, catId: Int) {
        val listener = object : ViewModelSubscribeListener<MarketCateResponse>(marketCateLiveData) {
            override fun onSuccess(resp: MarketCateResponse) {
                resp.data?.let {
                    if (it.category.isNotEmpty()) it.category[0].selected = true
                }
                super.onSuccess(resp)
            }
        }
        val marketCate =
            homeManager.secondCate(token, catId, listener)
        dispose.add(marketCate)
    }
}